package com.bnlr.lrparking.appui.carport;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.appui.carport.recommend.RecommendParkingActivity;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.adapter.ChooseCommunityAdapter;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.model.SelectDevelopersM;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.city.City;
import com.bnlr.lrparking.util.city.CityListAdapter;
import com.bnlr.lrparking.util.city.DBManager;
import com.bnlr.lrparking.util.city.LocateState;
import com.bnlr.lrparking.util.city.SideLetterBar;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.view.SampleEditTextWatcher;
import com.bnlr.lrparking.widget.popcity.PopupCheckBox;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 选择小区
 */
public class ChooseCommunityActivity extends BaseActivity {
    @BindView(R.id.tv_nav_title)
    TextView tvNavTitle;
    @BindView(R.id.pcb_choose_community)
    PopupCheckBox pcbChooseCommunity;
    @BindView(R.id.cet_choose_community)
    ClearEditText cetChooseCommunity;
    @BindView(R.id.tv_choose_community_search)
    TextView tvChooseCommunitySearch;
    @BindView(R.id.rv_choose_community)
    RecyclerView rvChooseCommunity;
    @BindView(R.id.rv_search_result)
    RecyclerView rvSearchResult;
    @BindView(R.id.rl_city_choose)
    RelativeLayout rlCityChoose;
    @BindView(R.id.ll_hint)
    LinearLayout llHint;
    @BindView(R.id.iv_hint)
    ImageView ivHint;
    @BindView(R.id.tv_hint_tips)
    TextView tvHintTips;
    private Unbinder unbinder;
    private String selectCity = "郑州市";
    private LocationClient mLocationClient = null;
    private LocationListener mLocationListener = null;
    private ChooseCommunityAdapter nearAdapter;
    private ChooseCommunityAdapter resultAdapter;
    private List<SelectDevelopersM.DataBean> nearData = new ArrayList<>();
    private List<SelectDevelopersM.DataBean> resultData = new ArrayList<>();
    private boolean isNeedResult = false;
    private CityListAdapter mCityAdapter = null;
    private static final String SELECT_XQ_CITY = "select_xq_city";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_community);
        unbinder = ButterKnife.bind(this);
        tvNavTitle.setText("选择小区");
        isNeedResult = getIntent().getBooleanExtra("is_from_park",false);
        String city = AppConfig.getInstance().getString(SELECT_XQ_CITY,"");
        if (TextUtils.isEmpty(city)) {
            initCity();

        } else {
            selectCity = AppConfig.getInstance().getString(SELECT_XQ_CITY,"");
            pcbChooseCommunity.setText(selectCity);
            initCity();
        }
        requestLocationPermission();
        initView();
        initListener();

    }

    private void initListener() {
        pcbChooseCommunity.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    rlCityChoose.setVisibility(View.VISIBLE);
                } else {
                    rlCityChoose.setVisibility(View.GONE);
                }
            }
        });
        tvChooseCommunitySearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestSearchParking();
            }
        });
    }

    /**
     * 初始化
     */
    private void initView() {
        rvChooseCommunity.setLayoutManager(new LinearLayoutManager(this));
        rvSearchResult.setLayoutManager(new LinearLayoutManager(this));
        nearAdapter = new ChooseCommunityAdapter(nearData);
        resultAdapter = new ChooseCommunityAdapter(resultData);
        rvChooseCommunity.setAdapter(nearAdapter);
        rvSearchResult.setAdapter(resultAdapter);
        requestNearParking();
        cetChooseCommunity.addTextChangedListener(new SampleEditTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                super.afterTextChanged(s);
                if (TextUtils.isEmpty(s.toString().replaceAll(" ",""))) {
                    tvChooseCommunitySearch.setVisibility(View.GONE);
                    rvSearchResult.setVisibility(View.GONE);
                } else {
                    pcbChooseCommunity.setChecked(false);
                    tvChooseCommunitySearch.setVisibility(View.VISIBLE);
                }
            }
        });
        cetChooseCommunity.setOnKeyListener(new View.OnKeyListener() {// 输入完后按键盘上的搜索键

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {// 修改回车键功能
                    // 先隐藏键盘
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                            getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

                    requestSearchParking();
                }
                return false;
            }
        });
        rvChooseCommunity.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                start(nearData.get(position).getId(),nearData.get(position).getName());
            }
        });
        rvSearchResult.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                start(resultData.get(position).getId(),resultData.get(position).getName());
            }
        });
    }

    /**
     * 初始化选择城市控件
     */
    private void initCity() {
        DBManager dbManager;
        List<City> mAllCities;
        final ListView mListView;
        SideLetterBar mLetterBar;
        mListView = (ListView) findViewById(R.id.listview_all_city);
        TextView overlay = (TextView) findViewById(R.id.tv_letter_overlay);
        mLetterBar = (SideLetterBar)findViewById(R.id.side_letter_bar);
        mLetterBar.setOverlay(overlay);
        mLetterBar.setOnLetterChangedListener(new SideLetterBar.OnLetterChangedListener() {
            @Override
            public void onLetterChanged(String letter) {
                int position = mCityAdapter.getLetterPosition(letter);
                mListView.setSelection(position);
            }
        });
        dbManager = new DBManager(this);
        dbManager.copyDBFile();
        mAllCities = dbManager.getAllCities();
        mCityAdapter = new CityListAdapter(this, mAllCities);
        mListView.setAdapter(mCityAdapter);
        mCityAdapter.updateLocateState(LocateState.SUCCESS, selectCity);
        mCityAdapter.setOnCityClickListener(new CityListAdapter.OnCityClickListener() {
            @Override
            public void onCityClick(String name) {
                //backWithData(name);
                if ("定位失败".equals(name)) {
                    return;
                }
                AppConfig.getInstance().putString(SELECT_XQ_CITY, name);
                selectCity = name;
                pcbChooseCommunity.setText(selectCity);
                pcbChooseCommunity.setChecked(false);
                rvSearchResult.setVisibility(View.GONE);
                requestNearParking();
            }

            @Override
            public void onLocateClick() {
                mCityAdapter.updateLocateState(LocateState.LOCATING, null);
            }
        });
    }

    /**
     * 请求定位权限
     */
    private void requestLocationPermission() {

        mLocationClient = new LocationClient(this, locationOption());
        mLocationListener = new LocationListener();
        mLocationClient.registerLocationListener(mLocationListener);
        PermissionUtils.permission("android.permission.ACCESS_COARSE_LOCATION").callback(
                new PermissionUtils.SimpleCallback() {
                    @Override
                    public void onGranted() {
                        mLocationClient.start();
                        mLocationClient.requestLocation();
                    }

                    @Override
                    public void onDenied() {
                        selectCity = "郑州市";
                        pcbChooseCommunity.setText(selectCity);
                        mCityAdapter.updateLocateState(LocateState.SUCCESS, "定位失败");
                        ToastUtils.showShort("请在设置--应用权限中打开定位权限");
                    }
                }
        ).request();
    }
    /**
     * 定位回调
     */
    private class LocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null) {
                return;
            }
            if (!TextUtils.isEmpty(bdLocation.getCity())) {
                String city = AppConfig.getInstance().getString(SELECT_XQ_CITY,"");
                if (TextUtils.isEmpty(city)) {
                    selectCity = bdLocation.getCity();
                    pcbChooseCommunity.setText(selectCity);
                }
                mCityAdapter.updateLocateState(LocateState.SUCCESS,  bdLocation.getCity());


            }

        }
    }

    /**
     * 请求停车场
      */
    private void requestNearParking() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetInSaleParking");
            mRequest.add("parkId", "0");
            mRequest.add("cityName", selectCity);
            mRequest.add("keyword", "");
            mRequest.add("pageindex", 1);
            mRequest.add("developerId", "0");
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<SelectDevelopersM>(baseContext, true, SelectDevelopersM.class) {
                        @Override
                        public void doWork(final SelectDevelopersM data, String code) {
                            if (code.equals("1")) {
                                if (data.getData()!= null && data.getData().size() > 0) {
                                    llHint.setVisibility(View.GONE);
                                    nearData.clear();
                                    nearData.addAll(data.getData());
                                    nearAdapter.notifyDataSetChanged();
                                }else {
                                    llHint.setVisibility(View.VISIBLE);
                                    ivHint.setImageResource(R.mipmap.nodata);
                                    tvHintTips.setText("该地区未查询到数据");
                                    nearData.clear();
                                    nearAdapter.notifyDataSetChanged();
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }
    private void requestSearchParking() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetInSaleParking");
            mRequest.add("parkId", "0");
            mRequest.add("cityName", selectCity);
            mRequest.add("keyword", cetChooseCommunity.getText().toString());
            mRequest.add("pageindex", 1);
            mRequest.add("developerId", "0");
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<SelectDevelopersM>(baseContext, true, SelectDevelopersM.class) {
                        @Override
                        public void doWork(final SelectDevelopersM data, String code) {
                            if (code.equals("1")) {
                                if (data.getData()!= null && data.getData().size() > 0) {
                                    rvSearchResult.setVisibility(View.VISIBLE);
                                    resultData.clear();
                                    resultData.addAll(data.getData());
                                    resultAdapter.notifyDataSetChanged();
                                } else {
                                    rvSearchResult.setVisibility(View.GONE);
                                    ToastUtils.showShort("未查询到数据");
                                }
                            } else {
                                ToastUtils.showShort(data.getMsg()+"");
                            }
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
        }
        if (mLocationClient != null) {
            mLocationClient.unRegisterLocationListener(mLocationListener);
            mLocationClient.stop();
            mLocationClient = null;
        }
        super.onDestroy();
    }

    /**
     * 设置定位参数
     *
     * @return
     */
    public LocationClientOption locationOption() {
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(false);
        option.setCoorType("bd09ll");
        option.setScanSpan(0);
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        return option;
    }
    private void start(int id,String name) {
        Params.IS_HAVE_CHOOSE_PARKING = true;
        Intent intent;
        if (isNeedResult) {
            intent = new Intent();
        } else {
            intent = new Intent(ChooseCommunityActivity.this, RecommendParkingActivity.class);
        }
        intent.putExtra("select_recommend_id",id);
        intent.putExtra("select_recommend_name",name);
        if (isNeedResult) {
            setResult(1011,intent);
        } else {
            startActivity(intent);
        }
        finish();
    }
}
